package controller;

public class CSPlayThread implements Runnable {

	private double deltaTime;
	
	private CSController csc;
	private boolean stop;
	
	public CSPlayThread(double deltaTime_, CSController csc_) {
		deltaTime = deltaTime_;
		csc = csc_;
		stop = false;
	}
	
	public boolean isAlive() {
	    return stop == false;
	}
	
	public void interrupt() {
        requestDeath();
    }
	
	public void run() {
		long calcDelay = 0;
		long time;
		while (!stop) {
			time = System.currentTimeMillis();
			if (!csc.updateWorldAndGUI(deltaTime/1000)) {
			    interrupt();
			}
			calcDelay = System.currentTimeMillis()-time;
			//System.out.println(time+" "+System.currentTimeMillis()+" "+calcDelay/1000+" "+deltaTime/1000);
			synchronized (this) {
				try {
					if (calcDelay < deltaTime) {
						wait((long)deltaTime/2);//-calcDelay);
					}
				}
				catch (InterruptedException e) {
				    interrupt();
					break;
				}
			}
		}
		csc.notifyPlayEnd();
	}
	
	public void requestDeath() {
		stop = true;
	}
}
